import { ContentScript } from '../utils/connect.js';
import React from 'react'
import ReactDOM from 'react-dom'
import ShadowView from './ShadowSetting'
/**
 * 给页面植入JS
 */
//修改此文件，必须重新reload 插件
console.log('Neo UI 开发助手加载成功', 2);
const devParam = 'develop_mode=1&resDomain=https://localhost'

const changeUrl = ()=>{
    let href = window.location.href
    //替换spa页面
    let newHref = href.replace('/index.action#/spa','')
    if(newHref.indexOf(devParam) < 0){
        if(newHref.indexOf('?') > -1){
            newHref += '&' + devParam
        }else{
            newHref += '?' + devParam
        }
    }
    console.log('newHref==',newHref)
    window.location.href = newHref
}

ContentScript.on('dayoneDev', () => {
    changeUrl()  
})


ContentScript.on('fetchNeoEntrys', (param, callback) => {
    fetch('/rest/bff/v4.0/mfEntrys').then(response=>response.json()).then(res=>{
        console.log('entrys===', res.data)

        callback(res.data)
    })
})


ContentScript.on('setNeoEntrys', (data) => {
    let neoEntrys = localStorage.getItem('neoEntrys')
    try{
        if(neoEntrys){
            neoEntrys = {...JSON.parse(neoEntrys), ...data}
        }else{
            neoEntrys = data
        }
        localStorage.setItem('neoEntrys',JSON.stringify(neoEntrys))
        console.log('写入localStorage成功',data)
    }catch(e){
        console.log('写入localStorage失败',data)
    }
})


ContentScript.on('mfswitch',(data)=>{
    toggleSwitch(data.mfswitch)
})

function toggleSwitch(mfswitch){
    const dom = document.getElementById('mfsettingroot');
    if(!dom){
        let div = document.createElement('div');
        div.id = 'mfsettingroot'
        document.body.appendChild(div);
        if(mfswitch){
            insertMFSetting(div);
        }else{
            ReactDOM.unmountComponentAtNode(div)
        }
    }else{
        if(mfswitch){
            insertMFSetting(dom);
        }else{
            ReactDOM.unmountComponentAtNode(dom)
        }
    }
}

function insertMFSetting(root){
    if(
        ~location.href.indexOf('localhost') ||
        ~location.href.indexOf('127.0.0.1') ||
        ~location.href.indexOf('xiaoshouyi') ||
        ~location.href.indexOf('ingageapp')
     
     ){
        ReactDOM.render(<ShadowView/>, root);
    }
    
}

chrome.storage.sync.get("mfswitch", ({mfswitch})=> {
    if (!chrome.runtime.lastError) {
      toggleSwitch(mfswitch)
    }
  });